# 第二周_第二节,字符串(字符序列)和字节序列
# 字符串编码,解码，编码错误

my_content = """
#编码
>>> a='我爱python!'.encode("unicode_escape")
>>> a
b'\\u6211\\u7231python!'

#解码
>>> b=a.decode("unicode_escape")
>>> b
'我爱python!'

#编码错误问题,导入chardet插件 以及忽略错误
>>> b='你'.encode("utf-8")+'订单'.encode("gbk")
>>> b
b'\xe4\xbd\xa0\xb6\xa9\xb5\xa5'
>>> import chardet
>>> chardet.detect(b)
{'encoding': 'ISO-8859-1', 'confidence': 0.73, 'language': ''}
b
#忽略错误编码
>>> b.decode("utf-8", errors='ignore')
'你'
#利用鬼符来替换
>>> b.decode("utf-8", errors='replace')
'你����'

字符串的CRUD操作

#Create(创建) +
>>> a="a"
>>> id(a)
2325906017584
>>> a += "python"
>>> a
'apython'
>>> id(a)
2325906101744

#Retrieve(检索)
>>> a="hello,python!"
>>> a[1]
'e'

#find和index(获取目标字符的索引值)
>>> a.find("l")
2
>>> a.find("b") # 查询不到是负数
-1
>>> a.find("y")
7

>>> a.index("h")
0
>>> a.index("j") # 查询不到报错
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found
>>>

#startwith和endwith
>>> a = "2020-12-25.hello,python.py"
>>> a.startswith("2020-12-25")
True
>>> a.endswith("py")
True
>>> a.startswith("2021")
False

#UPDATE(更新)
replace:
>>> a="good exvenning"
>>> a.replace("xven", "ve")
'good evening'

split:
>>> a ="good,morning"
>>> a.split(",")
['good', 'morning']
>>>

join:
>>> ",".join(a)
'g,o,o,d,,,m,o,r,n,i,n,g'
>>>  上面错误示范
>>> ",".join(a.split(","))
'good,morning'
>>>

#DELETE(删除)
strip 删除两边空格
>>> a="     hello, world      "
>>> a.strip()
'hello, world'

lstrip:
>>> a.lstrip()
'hella, world      '

rstrip:
>>> a.rstrip()
'     hella, world'

# format
#按传入参数默认顺序
>>> a = "ping"
>>> a = "ping"
>>> b = "pong"
>>> "play pingpong: {}, {}".format(a, b)
'play pingpong: ping, pong'

#按指定参数索引
>>> print("play pingpong: {a}, {b}, {a}, {b}".format(a='ping', b='pong'))
play pingpong: ping, pong, ping, pong

#按变量
>>> print(f"playing pingpong: {a}, {b}")
playing pingpong: ping, pong

#小数的表示
>>> "{:.2f}".format(3.1415926)
'3.14'

%表示
>>> "playing %s %s" % ("ping","pong")
'playing ping pong'
"""


# open函数打开一个文件, 没有文件会新建, 但是路劲不对会报错
# 指定文件名, 方法(读, 写, 追加), 编码格式
def my_write_txt():  # 写入文件
    output = open("第二周_第二节生成文件.txt", "w", encoding="utf-8")
    # 正式写入文件
    output.write(my_content)
    # 关闭文件句柄
    output.close()


def my_read_txt():  # 读取文件
    input = open("第二周_第二节生成文件.txt", "r", encoding="utf-8")
    content = input.read()
    print(content)


def my_add_txt():  # 追加文件
    output = open("第二周_第二节生成文件.txt", "a", encoding="utf-8")
    content = "\nhello, world"
    # 正式写入文件
    output.write(content)
    # 关闭文件句柄
    output.close()


if __name__ == "__main__":
    my_write_txt()
    my_read_txt()
    my_add_txt()

